package document;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collection;
import java.util.Hashtable;

/**
 * Holds all documents from that should be indexed
 * @author daniel
 *
 */
public class DocumentLibrary {
	
	public Hashtable<String, InputDocument> documents;
	
	public DocumentLibrary() {
		documents = new Hashtable<String, InputDocument>();
	}
	
	/**
	 * Reads all files in the specified folder and puts them into the collection
	 * @param folderPath
	 */
	public void initializeFrom(String folderPath) {
		int index = 0;
		
		File directory = new File(folderPath);
		File files[] = directory.listFiles();
		
		
		for (File f:files) 
		{
			if(!f.isDirectory())
			{

			String name = f.getName();

			// read content of file
			StringBuffer content = new StringBuffer();
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new FileReader(f));
				String line = "";

				while ((line = reader.readLine()) != null) {

					content.append(line).append(System.getProperty("line.separator"));

				}
				reader.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			
			InputDocument doc = new InputDocument(name, content.toString());
			documents.put(name, doc);
			index++;
			}
			
		}
	}
	
	public Collection<InputDocument> getInputDocuments() {
		return documents.values();
	}
	

	public void print() {
		System.out.println("Listing of all docs");
		for (InputDocument doc : documents.values()) {
			System.out.print(doc.getTitle() + ": " + doc.getContent());
		}
	}

	public int getNumbeOfDocuments() {
		return documents.size();
	}

}
